package game.objects.towers 
{
	import assets.Assets;
	import flash.display.BitmapData;
	import game.objects.actions.GoldIncomeAction;
	import game.objects.actions.ManaIncomeAction;
	import game.objects.Building;
	import game.objects.weapons.CannonWeapon;
	import game.objects.weapons.Weapon;
	import net.flashpunk.FP;
	import net.flashpunk.graphics.Graphiclist;
	import net.flashpunk.graphics.Image;
	import net.flashpunk.utils.Input;
	import net.flashpunk.utils.Key;
	/**
	 * ...
	 * @author Sulus Ltd.
	 */
	public class Tower extends Building
	{
		public var weaponAngle:Number = 0;
		public var weaponPower:Number = 0;
		
		private var guiOnline:Boolean = false;
		private var guiTarget:Image;
		
		public var arsenal:Array = [];
		public var currentWeapon:Weapon;
		
		public function Tower() 
		{
			controllable = true;
			
			
			setHitbox(32, 32, 0, 0);
			
			//AddAction(new GoldIncomeAction(10));
			//AddAction(new ManaIncomeAction(10));
			
			guiTarget = new Image(Assets.GUI_TARGET);
			guiTarget.visible = false;
			
			graphic = new Graphiclist(new Image(Assets.TOWER1_PNG), guiTarget);
			
			//TODO temp weps
			arsenal = [new CannonWeapon(),new CannonWeapon(),new CannonWeapon()];
			for (var i:int = 0; i < arsenal.length; i++)
			{
				arsenal[i].Init(this);
			}
		}
		
		override public function removed():void 
		{
			super.removed();
			for (var i:int = 0; i < arsenal.length; i++)
			{
				arsenal[i].Die();
			}

		}
		
		override public function update():void 
		{
			if (controlled)
			{
				if (Input.pressed(Key.SPACE) )
				{
					currentWeapon.Fire({x:x+16,y:y+16,angle:weaponAngle,power:weaponPower});
					//FinishTurn();
				}
				
				if (Input.mouseDown)
				{
					weaponAngle = -FP.angle(x + 16, y + 16, Input.mouseX + world.camera.x, Input.mouseY + world.camera.y) * Math.PI / 180;
					weaponPower = Math.min(FP.distance(x + 16, y + 16, Input.mouseX + world.camera.x, Input.mouseY + world.camera.y),100);
					
					UpdateGui();
				}
			}
			
			super.update();
		}
		
		private function UpdateGui():void 
		{
			guiTarget.x = Math.cos(weaponAngle) * weaponPower - guiTarget.width/2 + 16;
			guiTarget.y = Math.sin(weaponAngle) * weaponPower - guiTarget.height/2 + 16;
		}
		
		public function ShowGui(orly:Boolean):void
		{
			if (guiOnline == orly) return;
			guiOnline = orly;
			guiTarget.visible = orly;
			UpdateGui();
		}
		
		override public function SetControlled(orly:Boolean):void 
		{
			super.SetControlled(orly);
			ShowGui(controlled);
			if (arsenal.length>0)
			currentWeapon = arsenal[0];
		}
		
		public function WeaponFinished():void
		{
			FinishTurn();
		}
		
	}

}